<template>
  <div class="rq">
    <span
      class="tx"
      @mouseover="over($event, index)"
      @mouseout="out($event, index)"
      @click="cl($event, index)"
      v-for="(value, index) of dataArr"
      :key="index"
      v-insert="{ index, gs }"
    >
      {{ value }}
    </span>
  </div>
</template>

<script>
export default {
  data() {
    return {
      valueArr: [
        { id: 1, value: "古武机甲" },
        { id: 2, value: "未来世界" },
        { id: 3, value: "星际文明" },
        { id: 4, value: "超级科技" },
        { id: 5, value: "时空穿梭" },
        { id: 6, value: "进化变异" },
        { id: 7, value: "末世危机" },
      ],
      dsArr: [],
      clIndex: -1,
      gs: 3,
    };
  },
  props: {
    dataArr: {
      type: Array,
      required: true,
      default: () => {
        return [];
      },
    },
  },
  methods: {
    //封装删除所有子节点的方法
    //参数：e表示预删除所有子节点的父节点
    empty(e) {
      while (e.firstChild) {
        //清除点击事件
        e.firstChild.onclick = null;
        e.removeChild(e.firstChild);
      }
    },

    myCreateElement(type, className, value, attr) {
      let sp = document.createElement(type);
      let v = document.createTextNode(value);
      sp.appendChild(v);
      sp.className = "sCatalog " + className;
      if (attr) {
        sp.setAttribute(attr.name, attr.value);
      }
      return sp;
    },
    /**
     * 获取当前节点后指定类型的兄弟节点
     */
    BrotherByType(type, targetElement) {
      var brother = [];
      var p = targetElement.parentNode.children;
      var flag = false;
      for (var i = 0, pl = p.length; i < pl; i++) {
        if (flag) {
          if (p[i].tagName.toLowerCase() == type.toLowerCase()) {
            brother.push(p[i]);
          }
        }
        if (p[i] == targetElement) {
          flag = true;
        }
      }
      return brother;
    },
    /**
     * 获取指定类型的兄弟节点
     */
    AllBrotherByType(type, targetElement) {
      var brother = [];
      var p = targetElement.parentNode.children;
      for (var i = 0, pl = p.length; i < pl; i++) {
        if (p[i].tagName.toLowerCase() == type.toLowerCase()) {
          brother.push(p[i]);
        }
      }
      return brother;
    },
    /**
     * 节点后插入节点
     */
    myInsertAfter(newElement, targetElement) {
      var parent = targetElement.parentNode;
      if (parent.lastChild == targetElement) {
        parent.appendChild(newElement);
      } else {
        parent.insertBefore(newElement, targetElement.nextElementSibling);
      }
    },
    /**
     * 删除指定元素
     */
    deleteArray(value, arr) {
      arr.splice(arr.indexOf(value), 1);
    },
    over(event, index) {
      let el = event.currentTarget;
      let cns = el.className.split(" ");
      cns.push("over");
      el.className = cns.join(" ");
    },
    out(event, index) {
      let el = event.currentTarget;
      let cns = el.className.split(" ");
      this.deleteArray("over", cns);
      el.className = cns.join(" ");
    },
    selectData() {},
    cl(event, index) {
      let sp = document.querySelector("span.clAfter");
      //console.log(sp);
      if (sp) {
        let spC = sp.className.split(" ");
        this.deleteArray("clAfter", spC);
        sp.className = spC.join(" ");
      }

      let el = event.currentTarget;
      let cs = el.className.split(" ");
      if (!cs.includes("clAfter")) {
        cs.push("clAfter");
      }
      el.className = cs.join(" ");
      let v = el.value;
      // console.log(
      //   `根据点击的span的值${v}查询div应该有的内容，如果内容改变就改变div`
      // );
      //获取div
      let ds = this.BrotherByType("div", event.currentTarget);
      //获取div的class
      let cns = ds[0].className.split(" ");
      // console.log(cns);
      //显示或隐藏
      if (this.clIndex == index) {
        //和上次点击的是同一个
        //切换状态
        // console.log("第一个if");
        if (cns.includes("NoShow")) {
          this.deleteArray("NoShow", cns);
        } else {
          // console.log("消失");
          cns.push("NoShow");
        }
      } else {
        //和上次点击的不是同一个
        // console.log("第二个if");
        if (cns.includes("NoShow")) {
          //它对应的div没有被展示
          //关闭其他
          let allDiv = this.AllBrotherByType("div", el);
          // console.log(allDiv)
          for (let index = 0; index < allDiv.length; index++) {
            let element = allDiv[index];
            let classEle = element.className.split(" ");
            // console.log(classEle)
            if (!classEle.includes("NoShow")) {
              classEle.push("NoShow");
              element.className = classEle.join(" ");
            }
          }
          this.empty(ds[0]);
          //查询数据
          this.selectData();
          //1。valueArr即当前二级分类下的所有三级分类
          //2。当前二级分类下的所有作品
          //插入数据
          //TODO:
          this.valueArr.forEach((element) => {
            let tag = this.myCreateElement("span", "itemSt", element.value, {
              name: "find",
              value: element.id,
            });
            ds[0].appendChild(tag);
          });

          //展示div
          this.deleteArray("NoShow", cns);
        } else {
          //与上一个div是同一个
          this.empty(ds[0]);
          //更新数据
          //TODO:
          this.valueArr.forEach((element) => {
            let tag = this.myCreateElement("span", "itemSt", element.value, {
              name: "find",
              value: element.id,
            });
            ds[0].appendChild(tag);
          });
        }
        this.clIndex = index;
      }
      // console.log(`最后的log:${cns}`);
      ds[0].className = cns.join(" ");

      //为三级菜单绑定事件
      // console.log("三级菜单" + document.querySelectorAll(".sCatalog"));
      document.querySelectorAll(".sCatalog").forEach((element) => {
        element.onclick = () => {
          alert(123);
        };
      });
    },
  },
  directives: {
    insert: {
      //指令与元素成功绑定时（一上来）
      bind(element, binding) {},
      //指令所在元素被插入页面时
      inserted(element, binding, vnode) {
        // console.log(vnode);
        // console.log(binding);
        // const dsArr = binding.value.dsArr;
        const index = binding.value.index;
        // console.log(element.nextElementSibling)
        if (
          (index + 1) % binding.value.gs == 0 ||
          !element.nextElementSibling
        ) {
          let d = document.createElement("div");
          d.className = "NoShow ind";
          vnode.context.myInsertAfter(d, element);
          //记录
          // dsArr.push(d);
        }
      },
      //指令所在的模板被重新解析时
      update(element, binding) {},
    },
  },
};
</script>

<style>
.rq {
  /* 容器指定为Flex布局 */
  display: flex;
  /* 主轴为水平方向，起点在左端。 */
  flex-direction: row;
  /* 如果一条轴线排不下，换行。 */
  flex-wrap: wrap;
  /* 主轴上的对齐方式。两端对齐，项目之间的间隔都相等。 */
  justify-content: flex-start;
  /* 项目的第一行文字的基线对齐。 */
  align-items: baseline;
}
.ind {
  /* 容器指定为Flex布局 */
  display: flex;
  /* 主轴为水平方向，起点在左端。 */
  flex-direction: row;
  /* 如果一条轴线排不下，换行。 */
  flex-wrap: wrap;
  /* 主轴上的对齐方式。左对齐 */
  justify-content: center;
  /* 项目的第一行文字的基线对齐。 */
  align-items: baseline;
  background-color: #f7f6f2;
  width: 100%;
}
.tx {
  /* display:inline-block; */
  display: inline-flex;
  justify-content: center;
  flex-wrap: nowrap;
  width: 80px;
}
.itemSt {
  padding: 5px;
  /* width: 50px; */
}
.clBef {
  background-color: rgb(229, 230, 214);
}
.over {
  color: red;
}
.clAfter {
  background-color: #333333;
  color: #ffffff;
}
.rq {
  position: relative;
}
.NoShow {
  display: none;
}
</style>